package com.meiyuetao.myt.customer.web.action;

import java.util.Date;
import java.util.Map;
import java.util.Set;

import lab.s2jh.core.annotation.MetaData;
import lab.s2jh.core.context.SpringContextHolder;
import lab.s2jh.core.service.BaseService;
import lab.s2jh.core.web.view.OperationResult;
import lab.s2jh.ctx.FreemarkerService;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.rest.HttpHeaders;
import org.springframework.beans.factory.annotation.Autowired;

import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.meiyuetao.myt.core.web.MytBaseController;
import com.meiyuetao.myt.customer.entity.CustomerProfile;
import com.meiyuetao.myt.customer.entity.SmsLog;
import com.meiyuetao.myt.customer.entity.SmsLog.SmsChannelEnum;
import com.meiyuetao.myt.customer.service.CustomerProfileService;
import com.meiyuetao.myt.customer.service.QyqqSmsService;
import com.meiyuetao.myt.customer.service.SmsLogService;
import com.meiyuetao.myt.job.BusinessNotifyService;

@MetaData("SmsLogController")
public class SmsLogController extends MytBaseController<SmsLog, Long> {

    @Autowired
    private SmsLogService smsLogService;

    @Autowired
    private QyqqSmsService qyqqSmsService;

    @Autowired
    private CustomerProfileService customerProfileService;

    @Autowired
    private FreemarkerService freemarkerService;

    @Override
    protected BaseService<SmsLog, Long> getEntityService() {
        return smsLogService;
    }

    @Override
    protected void checkEntityAclPermission(SmsLog entity) {
        // Nothing
    }

    @Override
    @MetaData("创建")
    public HttpHeaders doCreate() {
        return super.doCreate();
    }

    @Override
    @MetaData("更新")
    public HttpHeaders doUpdate() {
        return super.doUpdate();
    }

    @Override
    @MetaData("保存")
    public HttpHeaders doSave() {
        return super.doSave();
    }

    @Override
    @MetaData("删除")
    public HttpHeaders doDelete() {
        return super.doDelete();
    }

    @Override
    @MetaData("查询")
    public HttpHeaders findByPage() {
        return super.findByPage();
    }

    public HttpHeaders doSend() {
        if (bindingEntity == null) {
            bindingEntity = new SmsLog();
        }
        String sendContent = this.getRequiredParameter("sendContent");
        String sendToList = this.getRequiredParameter("sendToList");
        String smsModel = this.getRequiredParameter("smsModel");
        sendSms(sendContent, sendToList, smsModel);
        bindingEntity.setSendContent(sendContent);
        bindingEntity.setSendTime(new Date());
        bindingEntity.setSendToList(sendToList);
        setModel(OperationResult.buildSuccessResult("发送中……"));
        smsLogService.save(bindingEntity);
        return buildDefaultHttpHeaders();
    }

    public HttpHeaders doSendFailure() {
        String sendContent = this.getRequiredParameter("sendContent");
        String sendToList = this.getRequiredParameter("failureToList");
        String smsModel = this.getRequiredParameter("smsModel");
        sendSms(sendContent, sendToList, smsModel);
        smsLogService.save(bindingEntity);
        setModel(OperationResult.buildSuccessResult("发送中……"));
        return buildDefaultHttpHeaders();
    }

    private void sendSms(String sendContent, String sendToList, String smsModel) {
        Set<String> filterPhones = Sets.newHashSet();
        String[] phoneList = sendToList.split("\n");
        for (String item : phoneList) {
            item = item.trim();
            if (StringUtils.isNotBlank(item) && item.length() == 11) {
                filterPhones.add(item);
            }
        }
        boolean dynamicContent = false;
        if (sendContent.indexOf("${") > -1) {
            dynamicContent = true;
        }
        String failureToList = "";

        for (String phone : filterPhones) {
            String contents = sendContent;
            if (dynamicContent) {
                Map<String, Object> params = Maps.newHashMap();
                CustomerProfile customerProfile = customerProfileService.findFirstByProperty("mobilePhone", phone);
                if (customerProfile == null) {
                    customerProfile = new CustomerProfile();
                }
                params.put("customerProfile", customerProfile);
                contents = freemarkerService.processTemplateByContents(sendContent, params);
            }

            BusinessNotifyService smsService = SpringContextHolder.getBean(BusinessNotifyService.class);
            if (SmsChannelEnum.STONG.equals(bindingEntity.getSmsChannel())) {
                smsService.sendMsgAsync(phone, contents, bindingEntity);
            } else if (SmsChannelEnum.YTX.equals(bindingEntity.getSmsChannel())) {
                smsService.sendTextSms(phone, contents, bindingEntity);
            } else if (SmsChannelEnum.YP.equals(bindingEntity.getSmsChannel())) {
                smsService.sendSmsByYunPian(phone, smsModel, contents);
            }

        }
        if (StringUtils.isNotBlank(failureToList)) {
            bindingEntity.setFailureToList(failureToList);
        } else {
            bindingEntity.setFailureToList(null);
        }
    }

}